package com.habdqn.easybuy.web.filter;

import com.habdqn.easybuy.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Xing.Jiejian
 * @date 2020/12/2
 */
@WebFilter(filterName = "UserFilter",urlPatterns = {"/manage/*","/shop/*","/order/*"})
public class UserFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 判断用户是否登录
        HttpSession session = ((HttpServletRequest)req).getSession();
        User user = (User) session.getAttribute("currentUser");
        if (user==null){
            // 将原本页面放入作用域
            String path = ((HttpServletRequest) req).getHeader("Referer");
            path = path.substring(path.indexOf(((HttpServletRequest) req).getContextPath()));
            session.setAttribute("localPath",path);
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.println("<script>");
            out.println("alert('请先登录！')");
            out.println("location.href='"+((HttpServletRequest) req).getContextPath()+"/login'");
            out.println("</script>");
        }else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
